package main

import (
	"flag"
	"fmt"
	uuid "github.com/satori/go.uuid"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net"
	"os"
	"os/signal"
	"rpc_demo/stock_srv/global"
	"rpc_demo/stock_srv/handler"
	"rpc_demo/stock_srv/initialize"
	"rpc_demo/stock_srv/proto"
	"rpc_demo/stock_srv/utils/register"
	"strconv"
	"syscall"
)

func main() {

	initialize.InitViperLogger()
	initialize.InitConfig()
	initialize.InitMysqlDb()

	IP := flag.String("ip", global.ServiceConfig.Host, "ip地址")
	Port := flag.Int("port", global.ServiceConfig.Port, "端口地址")

	server := grpc.NewServer()

	host := global.ServiceConfig.ConsulConfig.Host
	port := global.ServiceConfig.ConsulConfig.Port
	port1, _ := strconv.Atoi(port)
	tags := global.ServiceConfig.Tags
	name := global.ServiceConfig.Name
	serverId := uuid.NewV4().String()
	counsulRegister := register.NewCounsulRegister(host, port1)
	err := counsulRegister.ConsulRegister(global.ServiceConfig.Host, global.ServiceConfig.Port, name, tags, serverId)
	if err != nil {
		zap.S().Error("consul服务注册失败", err.Error())
		return
	}
	fmt.Println(*Port)

	proto.RegisterStocksServer(server, &handler.StockSrv{}) //库存服务
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
	if err != nil {
		panic(err)
	}
	go func() {
		err = server.Serve(listen)
		if err != nil {
			panic(err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = counsulRegister.CounsulDregister(serverId); err != nil {
		zap.S().Error("注销失败")
	}
	zap.S().Error("注销成功")
}
